package com.daoshu.mds.system.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.daoshu.component.exception.BusinessException;
import com.daoshu.component.page.PageConstants;
import com.daoshu.mds.constants.ConcatType;
import com.daoshu.mds.constants.LinkType;
import com.daoshu.mds.system.service.IGeneralConcatsService;
import com.daoshu.mds.system.service.IOConcatsService;
import com.daoshu.system.bo.ConcatsBO;
import com.daoshu.system.bo.ContentBO;
import com.daoshu.system.entity.*;
import com.daoshu.system.qo.PersonConcatsQO;
import com.daoshu.mds.system.mapper.PConcatsMapper;
import com.daoshu.mds.system.service.IPConcatsService;
import com.daoshu.system.bo.AccountBo;
import com.daoshu.system.bo.PersonContentBO;
import com.daoshu.system.constants.ClientType;
import com.daoshu.system.qo.PersonQO;
import com.daoshu.system.service.OrgFeignService;
import com.daoshu.system.service.PersonFeignService;
import com.daoshu.system.service.PersonStatusFeignService;
import com.daoshu.system.utils.RequestUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 *  人员通讯录服务实现类
 * </p>
 *
 * @author zhaoyanjiang
 * @since 2018-09-10
 */
@Service
public class PConcatsServiceImpl extends ServiceImpl<PConcatsMapper, PConcatsEntity> implements IPConcatsService {

	@Autowired private RequestUtils userUtil;
	@Autowired private PersonFeignService personService;
	@Autowired private OrgFeignService orgService;
	@Autowired private IOConcatsService oConcatsService;
	@Autowired private IGeneralConcatsService generalConcatsService;
	@Autowired private PConcatsMapper pConcatsMapper;
	@Autowired private PersonStatusFeignService personStatuService;
	
	@Override
	public boolean insert(PConcatsEntity entity) {
		entity.setAvailable(1);
		return this.save(entity);
	}

	@Override
	public boolean update(PConcatsEntity entity) {
		int result = pConcatsMapper.updateById(entity);
		return result > 0 ? true:false;
	}

	@Override
	public void defaultConcat(String id,String personId) {
		UpdateWrapper<PConcatsEntity> updateWrapper =  new UpdateWrapper<>();
		updateWrapper.eq("person_id_", personId).eq("default_", 1);
		PConcatsEntity pc = new PConcatsEntity();
		pc.setDefaultValue(0);
		this.update(pc, updateWrapper);
		PConcatsEntity entity = Optional.ofNullable(this.getById(id)).orElseThrow(()->{
			return new BusinessException(BusinessException.CODE_NO_DATE,"没有此联系方式");
		});
		entity.setDefaultValue(1);
		this.updateById(entity);
	}

	@Override
	public List<PConcatsEntity> getConcat(String personId) {
		if(StringUtils.isBlank(personId)) {
			throw new BusinessException(500, "联系人不能为空");
		}
		return this.list(new QueryWrapper<PConcatsEntity>().eq("person_id_", personId).eq("available_", 1));
	}

	@Override
	public PConcatsEntity getByContentAndType(String content, Integer type) {
		QueryWrapper<PConcatsEntity> queryWrapper = new QueryWrapper<PConcatsEntity>().eq("concat_number_", content).eq("available_", 1);
		if(type != null){
			queryWrapper.eq("concat_type_", type);

		}
		return this.getOne(queryWrapper);
	}

	@Override
	public IPage<ContentBO> queryPersonConcat(PersonConcatsQO qo) {
		PersonQO personqo = new PersonQO();
		BeanUtils.copyProperties(qo,personqo);
		IPage<PersonContentBO> personsBO = personService.queryPersonPage(personqo);
		List<ContentBO> contents = personsBO.getRecords().stream().map(m -> {
			ContentBO bo = new ContentBO();
			BeanUtils.copyProperties(m,bo);
			return bo;
		}).collect(Collectors.toList());
		IPage<ContentBO> persons = new Page<>();
		persons.setTotal(personsBO.getTotal());
		persons.setRecords(contents);
		List<ContentBO> list = Optional.ofNullable(contents).orElse(new ArrayList<>());
		List<String> personIds = new ArrayList<>();
		/*list.stream()
		.filter(a->!personIds.contains(a.getId()))
		.forEach(a->personIds.add(a.getId()));*/
		list.forEach(a->{
			if(!personIds.contains(a.getId())) {
				personIds.add(a.getId());
			}
		});
		AccountBo user = userUtil.getCurrentUser();
		// 设置是否常用联系人及设备类型
		List<PersonStatusEntity> personStatus = new ArrayList<>();
		if (null != qo.getPersonIds() && qo.getPersonIds().size() > 0) {
			personStatus = Optional.ofNullable(personStatuService.getPersonStatus(qo.getPersonIds())).orElse(new ArrayList<>());
		}

		List<GeneralConcatsEntity> gneeralConcat = Optional.ofNullable(generalConcatsService.list(new QueryWrapper<GeneralConcatsEntity>().eq("person_id_", user.getPersonBo().getId()).in("link_person_id_", qo.getPersonIds()))).orElse(new ArrayList<>());
		List<PersonStatusEntity> finalPersonStatus = personStatus;
		list.forEach(bo->{
			bo.setIsGeneralconcat(false);
			gneeralConcat.forEach(general->{
				if(general.getLinkPersonId()!=null&&general.getLinkPersonId().equals(bo.getId())) {
					bo.setGeneralId(general.getId());
					bo.setIsGeneralconcat(true);
				}
			});
			// 设置终端类型
			for(PersonStatusEntity status: finalPersonStatus) {
				if(status!=null&&status.getPersonId()!=null&&status.getPersonId().equals(bo.getId())) {
					bo.setClientType(status.getClientType());
					bo.setClientTypeName(ClientType.getClientType(bo.getClientType()).getTitle());
				}
			}
		});
		Collection<PConcatsEntity> concats = Optional.ofNullable(this.list(new QueryWrapper<PConcatsEntity>().in("person_id_", personIds).orderByAsc("sort_"))).orElse(new ArrayList<>());
		for(ContentBO person: list) {
			List<PConcatsEntity> temp = new ArrayList<>();
			List<PConcatsEntity> colonyCall = new ArrayList<>();
			List<PConcatsEntity> phone = new ArrayList<>();
			List<PConcatsEntity> restaCall = new ArrayList<>();
			List<PConcatsEntity> specicalCall = new ArrayList<>();
			List<PConcatsEntity> steatsCall = new ArrayList<>();
			for(PConcatsEntity concat: concats) {
				if(concat.getPersonId()!=null && concat.getPersonId().equals(person.getId())) {
					temp.add(concat);
					if(concat.getConcatType()!=null&&concat.getConcatType().equals(ConcatType.COLONY_CALL.getStatus())) {
						colonyCall.add(concat);
					}else if(concat.getConcatType()!=null&&concat.getConcatType().equals(ConcatType.PHONE.getStatus())) {
						phone.add(concat);
					}else if(concat.getConcatType()!=null&&concat.getConcatType().equals(ConcatType.RESTA_CALL.getStatus())) {
						restaCall.add(concat);
					}else if(concat.getConcatType()!=null&&concat.getConcatType().equals(ConcatType.SPECICAL_CALL.getStatus())) {
						specicalCall.add(concat);
					}else if(concat.getConcatType()!=null&&concat.getConcatType().equals(ConcatType.STEATS_CALL.getStatus())) {
						steatsCall.add(concat);
					}
					if(concat.getDefaultValue()!=null&&concat.getDefaultValue().equals(1)) {
						person.setDefaultConcat(concat.getConcatNumber());
						person.setDefaultConcatType(concat.getConcatType());
					}
				}
			}
			Map<String,Object> map = new HashMap<>();
			map.put("colonyCall", colonyCall.isEmpty()?null:colonyCall);
			map.put("phone", phone.isEmpty()?null:phone);
			map.put("restaCall", restaCall.isEmpty()?null:restaCall);
			map.put("specicalCall", specicalCall.isEmpty()?null:specicalCall);
			map.put("steatsCall", steatsCall.isEmpty()?null:steatsCall);
			person.setPersonConcats(temp);
			person.setConcats(map);
			person.setType(LinkType.PERSON.getStatus());
			person.setTypeName(LinkType.PERSON.getTitle());
			person.setPersonId(person.getId());
		}
		return persons;
	}

	@Override
	public List<ContentBO> queryPersonConcat(List<String> personIds) {
		List<ContentBO> result = new ArrayList<>();
		if(!personIds.isEmpty()) {
			PersonConcatsQO pConcatsQO = new PersonConcatsQO();
			pConcatsQO.setPersonIds(personIds);
			pConcatsQO.setStart(PageConstants.PAGE_NUM_START);
			pConcatsQO.setSize(personIds.size());
			List<ContentBO> personConcat = Optional.ofNullable(this.queryPersonConcat(pConcatsQO).getRecords()).orElse(new ArrayList<>());
			result = personConcat;
		}
		return result;
	}

	@Override
	public ConcatsBO getConcats(String content) {
		ConcatsBO bo = new ConcatsBO();
		PConcatsEntity p = this.getOne(new QueryWrapper<PConcatsEntity>().eq("concat_number_", content));
		if(p == null) {
			OConcatsEntity o = oConcatsService.getOne(new QueryWrapper<OConcatsEntity>().eq("concat_number_", content));
			if(o!=null) {
				OrganizationEntity org = orgService.getById(o.getOrganizationId());
				bo.setConcatNumber(content);
				bo.setConcatType(o.getConcatType());
				bo.setDefaultValue(o.getDefaultValue());
				bo.setId(o.getId());
				bo.setObjId(o.getOrganizationId());
				bo.setObjName(org.getName());
				bo.setType(2);
			}
		}else {
			PersonEntity person = personService.getById(p.getPersonId());
			bo.setConcatNumber(content);
			bo.setConcatType(p.getConcatType());
			bo.setDefaultValue(p.getDefaultValue());
			bo.setId(p.getId());
			bo.setObjId(p.getPersonId());
			bo.setObjName(person.getName());
			bo.setType(1);
		}
		return bo;
	}

	@Override
	public ConcatsBO getByObjIdAndContent(String content, String objId) {
		ConcatsBO bo = new ConcatsBO();
		QueryWrapper<PConcatsEntity> query = new QueryWrapper<PConcatsEntity>().eq("concat_number_", content);
		if(StringUtils.isNoneBlank(objId)){
			query.eq("person_id_", objId);
		}
		PConcatsEntity p = this.getOne(query);
		if(p == null) {
			OConcatsEntity o = oConcatsService.getOne(new QueryWrapper<OConcatsEntity>().eq("concat_number_", content).eq("organizationId", objId));
			if(o!=null) {
				OrganizationEntity org = orgService.getById(o.getOrganizationId());
				bo.setConcatNumber(content);
				bo.setConcatType(o.getConcatType());
				bo.setDefaultValue(o.getDefaultValue());
				bo.setId(o.getId());
				bo.setObjId(o.getOrganizationId());
				bo.setObjName(org.getName());
				bo.setType(2);
			}
		}else {
			PersonEntity person = personService.getById(p.getPersonId());
			bo.setConcatNumber(content);
			bo.setConcatType(p.getConcatType());
			bo.setDefaultValue(p.getDefaultValue());
			bo.setId(p.getId());
			bo.setObjId(p.getPersonId());
			bo.setObjName(person.getName());
			bo.setType(1);
		}
		return bo;
	}
}
